import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:jiang_yue/home/refresh.dart';
import 'package:jiang_yue/utils/cache/cache.dart';
import 'package:jiang_yue/utils/cache/UserCache.dart';

class PostPage extends StatefulWidget {
  @override
  _PostPageState createState() => _PostPageState();
}

class _PostPageState extends State<PostPage> {
  List cloneArticles = [];

  _handleGetPostList(int userID) async {
    Response response;
    if (userID == null) {
      response = await Dio().get("http://47.93.201.127:8080/jiangyue/postList", data: {});
    } else {
      response = await Dio().get("http://47.93.201.127:8080/jiangyue/postList", data: {"userID": userID});
    }

    if (response.data['success']) {
      articleInfos = response.data['data']['data'];

      // 该段代码限制setState的变化次数
      if (cloneArticles.length == 0) { // 如果cloneArticles.length==0,则重复调用
        setState(() {
          cloneArticles = List.from(articleInfos);
        });
      } else if (cloneArticles.length != articleInfos.length) {
        setState(() {
          cloneArticles = List.from(articleInfos);
        });
      } else {
        bool isChanged = false;
        for (var i = 0; i < articleInfos.length; i++) {
          if (articleInfos[i]['like'] != cloneArticles[i]['like']) {
            isChanged = true;
            break;
          }
        }

        if (isChanged) {
          setState(() {
            cloneArticles = List.from(articleInfos);
          });
        }
      }
    } else {
      print('报错： PostPage（获取帖子列表接口）');
    }
  }

  @override
  Widget build(BuildContext context) {
    if (userInfo.length != 0) {
      _handleGetPostList(userInfo[0].id);
    } else {
      _handleGetPostList(null);
    }

    return Refresh(articles: cloneArticles, callback: _handleGetPostList,);
  }
}
